package utils{
	import flash.display.Bitmap;
	import flash.display.Loader;
	import flash.display.LoaderInfo;
	import flash.events.Event;
	import flash.net.URLRequest;
	import flash.net.URLStream;
	
	public class ResourceLoader	{

		private static var urlRequest:URLRequest = new URLRequest();

		private static var loaderPool:Vector.<Loader> = new Vector.<Loader>;
		private static var streamPool:Vector.<URLStream> = new Vector.<URLStream>;
		
		public function ResourceLoader()	{
		}
		
		/**
		 * 加载总控制
		 * @param url 加载url
		 * @param complete 加载完成后执行函数
		 * */
		public static function load(url:String,complete:Function):void{
			urlRequest.url = url;
			var strArr:Array = url.split(".");
			var length:int = strArr.length;
			var format:String = strArr[length - 1];
			if(format == "jpg" || format == "png"){
				var loaderUnit:LoaderUnit = loaderPool.length?loaderPool.pop():new LoaderUnit();
				loaderUnit.url = url;
				loaderUnit.complete = complete;
				loadBMPHandler(loaderUnit);
			}else if(format == "xml"){
				var streamUnit:StreamUnit = streamPool.length?streamPool.pop():new StreamUnit();
				streamUnit.complete = complete;
				loadXML(streamUnit);
			}
		}
		
		/**
		 * 加载图片控制
		 * @param loader 加载图片Loader对象
		 * */
		private static function loadBMPHandler(loader:LoaderUnit):void{
			loader.load(urlRequest);
			loader.contentLoaderInfo.addEventListener(Event.COMPLETE,loadBMPComplete);
		}
		
		/**
		 * 加载图片完成后
		 * */
		private static function loadBMPComplete(e:Event):void{
			var loaderInfo:LoaderInfo = e.currentTarget as LoaderInfo;
			loaderInfo.removeEventListener(Event.COMPLETE,loadBMPComplete);
			var loaderUnit:LoaderUnit = loaderInfo.loader as LoaderUnit;
			var dataObj:Object = {content:Bitmap(loaderInfo.content).bitmapData,url:loaderUnit.url}
			if(loaderUnit.complete != null)loaderUnit.complete(dataObj);
			loaderPool.push(loaderUnit);
		}
		
		
		private static function loadXML(stream:StreamUnit):void{
			stream.load(urlRequest);
			stream.addEventListener(Event.COMPLETE,loadXMLComplete);
		}
		
		private static function loadXMLComplete(e:Event):void{
			var stream:StreamUnit = e.currentTarget as StreamUnit;
			stream.removeEventListener(Event.COMPLETE,loadXMLComplete);
			//转编码
			var info:String = stream.readMultiByte(stream.bytesAvailable , "UTF-8");
			if(stream.complete!=null)stream.complete(info);
			streamPool.push(stream);
		}
	}
}

import flash.display.Loader;
import flash.net.URLStream;

class LoaderUnit extends Loader{
	public var url:String;
	public var complete:Function;
}

class StreamUnit extends URLStream{
	public var complete:Function;
}



